/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef, useCallback, useEffect } from 'react';
import ProForm, { ProFormSelect, ProFormRadio, ProFormText } from '@ant-design/pro-form';
import { Row, Col, DatePicker, Form, Input } from 'antd';
import { initialValues, initialFormValues } from './utils';
import { getQueryConfig } from '@/services/operatorManagement';
import type { ProFormInstance } from '@ant-design/pro-form';
import { isArray } from 'lodash';
import type { Moment } from 'moment';
import moment from 'moment';
import KbAddressSelect from '@/components/KbAddressSelect';

const { RangePicker } = DatePicker;
const { TextArea } = Input;
const idRegExr = /[\r\n\;\,]/g;

const searchOptions = [
  { label: '订单号', value: 'order_id' },
  { label: '运单号', value: 'waybill_no' },
];

const textAreaSize = {
  minRows: 5,
  maxRows: 20,
};
interface FormProps {
  onChange?: Function;
  onSubmit: Function;
  brandPromise: Promise<any>;
  onQueryConfigChange: Function;
}
let promise: any = null;
const getQueryConfigPro = () => {
  if (!promise) {
    promise = getQueryConfig().then((res) => {
      const { data, success } = res;
      if (success) {
        return data;
      } else {
        return Promise.reject();
      }
    });
  }
  return promise;
};
const getChange = (data: Record<string, string>): { change: string; value: string | string[] } => {
  return {
    change: Object.keys(data)[0],
    value: Object.values(data)[0],
  };
};
const getQueryOptionsByType = (type: string, data: any) => {
  const response = data[type];
  return isArray(response)
    ? response.map((label, value) => ({
        label,
        value,
      }))
    : Object.keys(response).map((key) => ({
        value: key,
        label: response[key],
      }));
};

const vaildField = (values: string[], key: string) => {
  if (!values[key]) return;
  return !!values[key].filter((i: string) => {
    return !!i;
  }).length;
};

const OrderFrom: React.FC<FormProps> = (props) => {
  const { onSubmit, brandPromise, onQueryConfigChange } = props;
  const [searchType, setSearchType] = useState('order_id');

  const [sendAdd, setSendAdd] = useState<any[]>([]);
  const [receiveAdd, setReceiveAdd] = useState<any[]>([]);

  const handleToggleSearchType = (e: any) => {
    setSearchType(e.target.value);
  };
  const formRef = useRef<ProFormInstance>();
  const [currentDate, setDate] = useState<[Moment, Moment]>();
  const [areaVerify, setAreaVerify] = useState({
    order_id: {
      validateStatus: '',
      help: '',
    },
    waybill_no: {
      validateStatus: '',
      help: '',
    },
  });
  useEffect(() => {
    getQueryConfigPro().then((data: any) => {
      onQueryConfigChange(data);
    });
  }, []);
  const handleFormFieldsChange = useCallback(
    (data: any) => {
      const { value, change } = getChange(data);
      if (['order_id', 'waybill_no'].includes(change)) {
        const verifyCfg = {
          validateStatus: 'success',
          help: '单次批量查询最多支持20个运单号|订单号',
        };
        if (value.length > 20) {
          verifyCfg.validateStatus = 'error';
        }
        setAreaVerify({
          ...areaVerify,
          [change]: verifyCfg,
        });
      }
    },
    [areaVerify],
  );

  const handleFinish = async (values: any) => {
    const { date, order_id, waybill_no, send_address, receive_address } = values;
    const { validateStatus } = areaVerify[searchType];
    let sendAddress = {};
    let receiveAddress = {};
    if (validateStatus === 'success' || !validateStatus) {
      if (date) {
        values.start_time = moment(date[0]).format('YYYY-MM-DD');
        values.end_time = moment(date[1]).format('YYYY-MM-DD');
        delete values.date;
      }
      if (!vaildField(values, 'order_id')) {
        delete values.order_id;
      }
      if (!vaildField(values, 'waybill_no')) {
        delete values.waybill_no;
      }
      if (order_id) {
        values.order_id = order_id.filter((i: string) => !!i);
      }
      if (waybill_no) {
        values.waybill_no = waybill_no.filter((i: string) => !!i);
      }

      if (send_address) {
        const [shipper_province = '', shipper_city = '', shipper_county = '']: string[] =
          sendAdd?.map((item) => item.label);
        sendAddress = {
          shipper_province,
          shipper_city,
          shipper_county,
        };
        delete values.send_address;
      }
      if (receive_address) {
        const [shipping_province = '', shipping_city = '', shipping_county = '']: string[] =
          receiveAdd?.map((item) => item.label);
        receiveAddress = {
          shipping_province,
          shipping_city,
          shipping_county,
        };
        delete values.receive_address;
      }

      onSubmit({
        ...values,
        ...sendAddress,
        ...receiveAddress,
      });
    }
  };

  const handleCalendarChange = (date: any) => {
    setDate(date);
  };
  const handleDisabledDate = useCallback(
    (current: any) => {
      const [y, m, d] = moment(current).format('YYYY-MM-DD').split('-');
      const [ny, nm, nd] = moment().format('YYYY-MM-DD').split('-');
      if (
        parseInt(ny) < parseInt(y) ||
        (nm <= m && ny <= y && parseInt(nd) < parseInt(d)) ||
        (nm < m && ny <= y)
      ) {
        return true;
      }
      if (currentDate) {
        const selectedDate = currentDate[0] || currentDate[1];
        const currentD = Math.abs(moment(current).diff(moment(selectedDate), 'day'));
        const disabled = currentD > 31;
        return disabled;
      }
      return false;
    },
    [currentDate],
  );
  return (
    <ProForm
      layout='horizontal'
      submitter={{
        resetButtonProps: {
          style: { marginLeft: 100 },
        },
      }}
      onValuesChange={handleFormFieldsChange}
      initialValues={initialValues}
      onFinish={handleFinish}
      formRef={formRef}
    >
      <Row justify='space-between'>
        <Col xs={24} sm={24} md={16} lg={16} xl={16}>
          <Row justify='space-around' gutter={2}>
            <Col md={10} xl={10} xs={24} sm={24}>
              <Form.Item name='date' label='下单时间' initialValue={initialFormValues.datePicker}>
                <RangePicker
                  format='YYYY-MM-DD'
                  disabledDate={handleDisabledDate}
                  onCalendarChange={handleCalendarChange}
                />
              </Form.Item>
              <ProFormText label='收件人手机号' name='shipping_mobile' />

              <ProFormSelect
                label='订单渠道'
                request={async () =>
                  getQueryConfigPro().then((res: any) => getQueryOptionsByType('channel', res))
                }
                name='channel'
              />
              <ProFormSelect
                label='接单状态'
                request={async () =>
                  getQueryConfigPro().then((res: any) =>
                    getQueryOptionsByType('receive_status', res),
                  )
                }
                name='receive_status'
              />
              <ProFormSelect
                label='订单类型'
                request={async () => brandPromise}
                name='order_type'
              />
              <ProForm.Item label='寄件地址' name={'send_address'}>
                <KbAddressSelect
                  level={2}
                  placeholder='请选择省市区/县'
                  onChange={(_, optin) => setSendAdd(optin)}
                />
              </ProForm.Item>
            </Col>
            <Col md={10} xl={10} xs={24} sm={24}>
              <ProFormText label='寄件人手机号' name='shipper_mobile' />
              <ProFormSelect
                label='订单状态'
                request={async () =>
                  getQueryConfigPro().then((res: any) => getQueryOptionsByType('order_status', res))
                }
                name='order_status'
              />
              <ProFormSelect
                label='揽收状态'
                request={async () =>
                  getQueryConfigPro().then((res: any) =>
                    getQueryOptionsByType('collect_status', res),
                  )
                }
                name='collect_status'
              />
              <ProFormSelect
                label='助力状态'
                request={async () =>
                  getQueryConfigPro().then((res: any) => getQueryOptionsByType('help_status', res))
                }
                name='help_status'
              />
              <ProFormText label='交易流水号' name='trade_number' />
              <ProForm.Item label='收件地址' name={'receive_address'}>
                <KbAddressSelect
                  level={2}
                  placeholder='请选择省市区/县'
                  onChange={(_, optin) => setReceiveAdd(optin)}
                />
              </ProForm.Item>
            </Col>
          </Row>
        </Col>
        <Col xs={24} sm={24} md={8} lg={8} xl={8}>
          <ProFormRadio.Group
            radioType='button'
            fieldProps={{
              value: searchType,
              onChange: handleToggleSearchType,
            }}
            options={searchOptions}
          />
          <Form.Item
            name={searchType}
            hasFeedback
            {...areaVerify[searchType]}
            normalize={(value) => {
              const ids = value.replace(idRegExr, ',')?.split(',');
              console.log('ids', ids);
              return ids;
            }}
          >
            <TextArea showCount autoSize={textAreaSize} />
          </Form.Item>
        </Col>
      </Row>
    </ProForm>
  );
};
export default OrderFrom;
